<template>
  <div class="tags">
    <el-tag
      v-for="(tag, index) in dynamicTags"
      :key="tag"
      class="mx-1"
      :closable="index != 0"
      :disable-transitions="false"
      @close="handleClose(tag.title, index, tag.path)"
      :effect="tag.path == $route.path ? 'dark' : 'light'"
      @click="$router.push(tag.path)"
    >
      {{ tag.title }}
    </el-tag>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useTagsStore } from "../store/tags";
import { useRouter, onBeforeRouteUpdate, useRoute } from "vue-router";
interface tagItem {
  title: string;
  path: string;
}
const TagsStore = useTagsStore();
const dynamicTags = ref<Array<tagItem>>([]);
const router = useRouter();
const route = useRoute();
// 初始渲染
onMounted(() => {
  dynamicTags.value = TagsStore.dynamicTags;
});
// 在存储变化的时候执行
TagsStore.$subscribe((mutation, state) => {
  dynamicTags.value = state.dynamicTags;
});

// 点击删除
function handleClose(tag: string, i: number, path: string) {
  let index = dynamicTags.value?.findIndex(
    (item) => item.title == tag
  ) as number;
  if (path == route.path) {
    router.push(dynamicTags.value[i - 1].path);
  }
  TagsStore.$patch((state) => {
    state.dynamicTags?.splice(index, 1);
  });
}
onBeforeRouteUpdate((to, from) => {});
// 是否选择
const isSelect = ref<boolean>(false);

//
</script>

<style lang="scss" scoped>
.tags {
  line-height: 60px;
  .el-tag {
    cursor: pointer;
    height: 28px;
  }
}
</style>
